﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using FRL.DebtChased.Website;
using FRL.DebtChased.Repository;

namespace WebApplication.Finance
{

	/// <summary>
	/// Declaration of ImportWizard
	/// </summary>
	public partial class ImportWizard : System.Web.UI.Page
	{

		/////////////////////////////////////////////////////////////
		// Attributes

		/////////////////////////////////////////////////////////////
		// Event handlers

		protected void Page_Load(object sender, EventArgs e)
		{

			// If this is a postback...
			if (this.IsPostBack)
			{

			}
			else
			{

				// Declare an entities object
				using (DebtChasedEntities ent = new DebtChasedEntities())
				{

					// Load the clients
					/*
					cboClient.BindToDictionary(rep.LoadClientDictionary());
					cboClient.Items.Insert(0, new ListItem("[Select From List]", "0"));
					cboClient.SelectedIndex = 0;
					 */

				}

				// Hide the template controls
				pnlTemplates.Visible = false;
				pnlUpload.Visible = false;

			}

		}

		protected void cboClient_SelectedIndexChanged(object sender, EventArgs e)
		{

			/*
			// Get the selected client
			int iClientId = int.Parse(cboClient.SelectedValue);
			if (iClientId != 0)
			{

				// Load the templates for this client
				SqlDataRepository rep = new SqlDataRepository();
				cboTemplate.BindToDictionary(rep.LoadImportTemplateDictionary(iClientId));

				// Show/hide controls
				pnlTemplates.Visible = true;
				cboTemplate.Visible = (cboTemplate.Items.Count > 0);
				lbNoTemplates.Visible = (cboTemplate.Items.Count == 0);
				pnlUpload.Visible = (cboTemplate.Items.Count > 0);

				// Select top item
				if (cboTemplate.Items.Count > 0)
					cboTemplate.SelectedIndex = 0;

			}
			else
			{

				// Show/hide controls
				pnlTemplates.Visible = false;
				pnlUpload.Visible = false;

			}
			 */
			

		}

		protected void lnkNewTemplate_Click(object sender, EventArgs e)
		{

			// Create a new template
			Response.Redirect("~/Finance/EditImportTemplates.aspx");

		}

		protected void ButImport_Click(object sender, EventArgs e)
		{

			// Track errors
			string strErrors = null;

			// Check the controls
			this.Page.Validate();
			if (!this.Page.IsValid)
				strErrors = "One or more errors are preventing data import.";

			/*
			// If that worked...
			if (strErrors == null)
			{

				// Check the import-data object
				ImportData.eStatus Status = MySession.GetImportStatus();
				if (Status == ImportData.eStatus.Importing)
					strErrors = "Another data file is currently being processed.  Please wait a few seconds and try again.";

			}
			*/

			// If that worked...
			if (strErrors == null)
			{

				try
				{

					/*
					// Get my session
					MySession mySession = MySession.BindMySession();

					// Get selected currency, country and letter
					string strDefaultCountryCode = cboCountry.SelectedValue;
					MoneyDecimal.eCurrency DefaultCurrency = MoneyDecimal.ParseCurrencyCode(cboCurrency.SelectedValue);
					int iLetterId = int.Parse(cboLetter.SelectedValue);

					// get customer user id and account user id
					int iCustomerUserId = 0;
					int iAccountUserId = 0;
					if (mySession.IsAdmin)
					{
						iCustomerUserId = int.Parse(cboCustomerUser.SelectedValue);
						iAccountUserId = int.Parse(cboAccountUser.SelectedValue);
					}
					else
					{
						iCustomerUserId = mySession.UserID;
						iAccountUserId = mySession.ParentUserID.Value;
					}
					 */

					// Check if uploader was submitted
					if (FileUpload.PostedFile.ContentLength == 0)
						strErrors = "Please specify an Excel data file.";
					else if (FileUpload.PostedFile.ContentLength > (1024 * 1024 * 1))
						strErrors = "Too large.  Imported files can be up to 1Mb.";
					else if (
						(!FileUpload.PostedFile.FileName.EndsWith(".xls", StringComparison.CurrentCultureIgnoreCase))
						&&
						(!FileUpload.PostedFile.FileName.EndsWith(".xlsx", StringComparison.CurrentCultureIgnoreCase))
					)
						strErrors = "Only Excel files in xls and xlsx format can be imported.";
					else
					{

						// Get the target directory
						string strTargetFilepath = Path.Combine(
							Server.MapPath("~/UploadWorkspace"),
							String.Format("{0}{1}", Guid.NewGuid(), Path.GetExtension(FileUpload.PostedFile.FileName))
						);

						// Upload the file
						//FileUpload.PostedFile.SaveAs(strTargetFilepath);

						/*
						// Start the worker thread
						ImportData importData = MySession.BindImportData();
						strErrors = importData.Import(
							strTargetFilepath,
							DefaultCurrency,
							strDefaultCountryCode,
							iLetterId,
							iCustomerUserId,
							iAccountUserId,
							true
						);
						 */

					}

				}
				catch (Exception x)
				{

					// Update error
					strErrors = String.Format("Failed to upload file.  {0}", x.Message);

				}

				// If that worked...
				if (strErrors == null)
				{

					// Move to the pending page
					//Response.Redirect("ImportPending.aspx");

				}

			}

			// Update errors
			(this.Master as FinanceMaster).ErrorMessage = strErrors;

		}

	}

}